# -*- coding: utf-8 -*-

from qqbot import QQBotSlot as qqbotslot, RunBot
import time
import random
import time
import robotSqlite
@qqbotslot
def onQQMessage(bot, contact, member, content):
    print "contact is %s type is %s , qq is %s, name is %s,content is %s" % (contact,contact.ctype,contact.qq,contact.name,content)
    if contact.ctype == 'group':
        #群聊
        print "member is %s" % member.name
        if '@ME' in content:
            saveUserToMemory(member)
            if '-t' in content:
                bot.SendTo(contact, getUserPastTime(member))
            else:
                bot.SendTo(contact, handleRandom(member, content))
    else:
        #私聊  暂时还未排除可能会有其他情况
        saveUserToMemory(contact)
        if content == '-hello':
            bot.SendTo(contact, '你好，我是QQ机器人')
        elif content == '-stop':
            bot.SendTo(contact, 'QQ机器人已关闭')
            bot.Stop()
        elif '-t' in content:
            bot.SendTo(contact, getUserPastTime(contact))
        else:
            bot.SendTo(contact, '收到你的消息了！不过我暂时还不能识别，谢谢你帮助我成长！')

def handleRandom(member, message):
    if '-r' in message:
        num = '%r' % random.randint(0,100)
        return ''+member.name+'掷了一个骰子，点数是'+num
    else:
        return ''+member.name+',  是在叫我吗？'

def sendUserInfo(member):
    num = checkUserIFExists('messageCount', member.qq)
    time = checkUserIFExists('createTime', member.qq)
    print "asdfa"
    sql = '''SELECT julianday('now')-julianday(%s)''' % time

#数据库部分
conn = robotSqlite.get_conn('')
#存储用户

def getUserPastTime(member):
    timeayy = checkUserIFExists('createTime', member.qq)
    nowtt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    sql = '''SELECT julianday( datetime('%s'))-julianday( datetime('%s'))''' % (nowtt,timeayy)
    print sql
    cu = conn.cursor()
    cu.execute(sql)
    num = cu.fetchone()
    
    then = num[0]
    dayh = int(then)
    last = then % 1
    hhh = last * 24
    hhn = int(hhh)
    str = "我们才刚刚认识"
    if dayh > 0:
        str = "%r天%r小时" % (dayh, hhn)
    elif hhn > 0:
        str = "%r个小时" % hhn
    else:
        last = hhh % 1
        minn = last * 60
        minint = int(minn)
        str = "我们才刚刚认识了%r分钟" % minint
        return str
    return "我们已经认识了"+str+"了"


def saveUserToMemory(member):
    if checkUserIFExists('*', unicode(member.qq)) is not None:
        #此用户已存在，更新它和机器人发过的消息数量
        updateUsrInfo(member.qq)
    else:
        #用户数据不存在，插入此数据
        print member.qq
        print member.name
        qqs = u'%r' % member.qq
        names = u'%r' % member.name
        
        #s.decode('utf-8').encode('gb2312')
        #qqs.decode('utf-8').encode('gb2312')
        #names.decode('utf-8').encode('gb2312')
        sql = '''INSERT INTO user (qq, name, createTime, messageCount, tempValue) values ('%s', '%s', ?, ?, ?);''' % (member.qq, member.name)
        data = [(time.strftime("%Y-%m-%d %H:%M:%S"), 1, u'0')]
        robotSqlite.save(conn, sql, data)
    return


#更新用户的消息数量
def updateUsrInfo(value):
    num = checkUserIFExists('messageCount', value)
    print num
    setNum = num+1
    if num is not None:
        sql = '''UPDATE user SET messageCount = %r WHERE qq = ?''' % setNum
        data = [(value)]
        robotSqlite.update(conn, sql, data)
    fetchoneValueByUser(value)

#更新用户存储的数值
def setTempValue(value, qq):
    sql = '''UPDATE user SET tempValue = %s WHERE qq = ?''' % value
    data = [(qq)]
    robotSqlite.update(conn, sql, data)
    fetchoneValueByUser(qq)

#插入值
def insertExample():
    sql = '''INSERT INTO user (qq, name, createTime, messageCount, tempValue) values (?, ?, ?, ?, ?);'''
    data = [(u'123456789', u'测试',time.strftime("%Y-%m-%d %H:%M:%S"), 0, u'0'),
            (u'123456790', u'uu', time.strftime("%Y-%m-%d %H:%M:%S"), 0, u'0'),
            (u'123456879', u'ee', time.strftime("%Y-%m-%d %H:%M:%S"), 0, u'0')]
    robotSqlite.save(conn, sql, data)

#查询一个字段
def checkUserIFExists(result, qq):
    sql = "SELECT %s FROM user WHERE qq = ?" % (result)
    data = qq
    user = robotSqlite.fetchone(conn, sql, data)
    if user is None:
        return None

    if len(user) > 0:
            return(user[0])
    return None

#查询一条数据
def fetchoneValueByUser(qq):
    sql = "SELECT * FROM user WHERE qq = ?"
    data = qq
    user = robotSqlite.fetchone(conn, sql, data)


def initDataBase():
    #若已存在，则不会创建
    create_table_sql =  '''CREATE TABLE IF NOT EXISTS 'user' (
        'id' INTEGER PRIMARY KEY,
        'qq' varchar(15) NOT NULL,
        'name' varchar(20) NOT NULL,
        'createTime' TimeStamp NOT NULL DEFAULT (datetime('now','localtime')),
        'messageCount' int(11) NOT NUll,
        'tempValue' varchar(20)
        );'''
    robotSqlite.create_table(conn, create_table_sql)

if __name__ == '__main__':
    initDataBase()
    #insertExample()
    RunBot()
